/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package com.je.bpm.engine.impl.cmd;

import com.je.bpm.common.operation.OperatorEnum;
import com.je.bpm.core.model.BpmnModel;
import com.je.bpm.core.model.FlowElement;
import com.je.bpm.core.model.FlowNode;
import com.je.bpm.core.model.SequenceFlow;
import com.je.bpm.core.model.task.KaiteBaseUserTask;
import com.je.bpm.core.model.task.KaiteLoopUserTask;
import com.je.bpm.core.model.task.KaiteTask;
import com.je.bpm.engine.ActivitiException;
import com.je.bpm.engine.ActivitiObjectNotFoundException;
import com.je.bpm.engine.RepositoryService;
import com.je.bpm.engine.TaskService;
import com.je.bpm.engine.history.HistoricTaskInstance;
import com.je.bpm.engine.impl.HistoricTaskInstanceQueryImpl;
import com.je.bpm.engine.impl.interceptor.Command;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.entity.TaskEntity;
import com.je.bpm.engine.task.Task;
import com.je.bpm.runtime.shared.identity.ResultUserParser;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 获取提交任务节点信息
 */
public class FindCurrentElementAssigneeCmd implements Command<Object>, Serializable {

    //构建人员部门信息的时候如果是委托或者转办，设置为默认不可多选
    public static final String[] NO_MULTIPLE = new String[]{OperatorEnum.TASK_DELEGATE_OPERATOR.getId(),
            OperatorEnum.TASK_TRANSFER_OPERATOR.getId()};

    //构建人员部门信息的时候如果是委托或者转办， 设置为默认不添加自己的信息
    public static final String[] NO_ADD_OWN = new String[]{OperatorEnum.TASK_DELEGATE_OPERATOR.getId(),
            OperatorEnum.TASK_TRANSFER_OPERATOR.getId()};

    private static final long serialVersionUID = 1L;
    protected String target;
    protected String taskId;
    protected String pdid;
    protected Map<String, Object> bean;
    protected String prod;
    protected ResultUserParser resultUserParser;
    protected String operationId;

    public FindCurrentElementAssigneeCmd(String pdid, String taskId, String target, Map<String, Object> bean, String prod, String operationId) {
        this.taskId = taskId;
        this.pdid = pdid;
        this.target = target;
        this.bean = bean;
        this.prod = prod;
        this.operationId = operationId;
    }

    @Override
    public Object execute(CommandContext commandContext) {
        resultUserParser = commandContext.getProcessEngineConfiguration().getResultUserParser();
        TaskEntity task = commandContext.getTaskEntityManager().findById(taskId);
        if (task == null) {
            throw new ActivitiObjectNotFoundException("Cannot find task with id " + taskId, Task.class);
        }
        return findCurrentElement(commandContext, task);
    }

    private Object findCurrentElement(CommandContext commandContext, TaskEntity task) {
        List<Object> result = new ArrayList<>();
        RepositoryService repositoryService = commandContext.getProcessEngineConfiguration().getRepositoryService();
        BpmnModel bpmnModel = repositoryService.getBpmnModel(task.getProcessDefinitionId());
        FlowElement taskFlowElement = bpmnModel.getFlowElement(task.getTaskDefinitionKey());

        if (taskFlowElement == null) {
            throw new ActivitiException(String.format("Can't find task %s definiton from the process.", task.getName()));
        }
        Boolean multiple = true;
        Boolean addOwn = true;
        KaiteTask kaiteTask = (KaiteTask) taskFlowElement;
        if (taskFlowElement instanceof KaiteLoopUserTask) {
            result.add(kaiteTask.getIncomingFlows().get(0));
            multiple = false;
            addOwn = false;
        }

        if (Arrays.asList(NO_MULTIPLE).contains(operationId)) {
            multiple = false;
        }
        if (Arrays.asList(NO_ADD_OWN).contains(operationId)) {
            addOwn = false;
        }
        FlowNode flowNode = null;
        //如果是转办操作
        if(OperatorEnum.TASK_TRANSFER_OPERATOR.getId().equals(operationId)){
            List<SequenceFlow> incomingFlows = ((KaiteTask) taskFlowElement).getIncomingFlows();
            for (SequenceFlow sequenceFlow : incomingFlows) {

                FlowElement userTask = bpmnModel.getMainProcess().getFlowElement(sequenceFlow.getSourceRef());
                if (userTask != null) {
                    if (getNodeInfo(commandContext, task.getProcessInstanceId(), userTask)) {
                        flowNode = (FlowNode) userTask;
                    }
                }
            }
        }
        return buildUsersInfo(addOwn, multiple, (KaiteBaseUserTask) taskFlowElement, commandContext.getProcessEngineConfiguration().getTaskService(), flowNode);
    }
    private Boolean getNodeInfo(CommandContext commandContext, String piid, FlowElement userTask) {
        HistoricTaskInstanceQueryImpl historicTaskInstanceQuery = new HistoricTaskInstanceQueryImpl();
        historicTaskInstanceQuery.processInstanceId(piid);
        historicTaskInstanceQuery.taskDefinitionKey(userTask.getId());
        historicTaskInstanceQuery.orderByTaskCreateTime().desc();
        List<HistoricTaskInstance> links = commandContext.getProcessEngineConfiguration().getHistoricTaskInstanceEntityManager()
                .findHistoricTaskInstancesByQueryCriteria(historicTaskInstanceQuery);
        if (links.size() > 0) {
            return true;
        } else {
            return false;
        }
    }

    private Object buildUsersInfo(Boolean addOwn, Boolean multiple, KaiteBaseUserTask kaiteBaseUserTask,
                                  TaskService taskService, FlowNode flowNode) {
        List<Object> listUser = new ArrayList<>();
        listUser.add(taskService.getAssignment(addOwn, multiple, pdid, kaiteBaseUserTask, taskId, prod, bean, flowNode));
        return listUser;
    }


}
